/**
 * @Project: Runer
 * @Title: ActivityPersonInfo.java
 * @Package com.runlooker.runer.contact
 * @author town
 * @date 2014-5-31 下午1:19:37
 * @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
 * @version V1.0
 */
package com.runlooker.runer.ui.personInfo;

import java.util.LinkedList;
import java.util.List;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListPopupWindow;
import android.widget.TextView;

import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.dao.PersonInfoDao;
import com.runlooker.runer.dao.PresenceDao;
import com.runlooker.runer.dao.RosterEntryDao;
import com.runlooker.runer.entity.LocalRosterEntity;
import com.runlooker.runer.entity.PersonInfoEntity;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseActivity;
import com.runlooker.runer.ui.chat.ChatActivity;
import com.runlooker.runer.util.L;
import com.runlooker.runer.util.NetworkUtil;
import com.runlooker.runer.util.T;

/**
 * @ClassName ActivityPersonInfo
 * @Description 模块描述
 * @author town
 * @Date 2014-5-31
 */
public class PersonInfoActivity extends BaseActivity implements
		OnClickListener, OnItemClickListener {

	public final static String INTENT_ACCOUNT = "account";
	public final static String tag = PersonInfoActivity.class.getSimpleName();
	public final static int GET_PERSONINFO = 0x002;// 成功获得用户信息
	public final static int GET_PERSONINFO_EXCEPTION = 0x006;// 成功获得用户信息
	public final static int ROSTER_CHANGE_SUCCESS = 0x001;// roster更新成功
	public final static int ROSTER_CHANGE_EXCEPTION = 0x005;// roster更新失败

	public final static int DELETE_ACTION = 0x003;// 删除好友操作
	public final static int ADD_ACTION = 0x004;// 添加好友操作
	private XmppService mXmppService;

	private Button button1;
	private Button mSendMsgBtn;
	private Button mAddfriendBtn;
	private ImageView mImg1Iv;
	private ImageView mImg2Iv;
	private ImageView mImg3Iv;
	private ImageView mMenuIv;
	private TextView mNickNameTv;
	private TextView mAreaTv;
	private Thread mThread;
	private TextView mAccountTv;
	private ListPopupWindow mMenuWindow;

	private MenuAdapter mMenuAdapter;
	private PersonInfoEntity mInfo;
	private PersonInfoDao mPersonInfoDao;
	private PresenceDao mPresenceDao;
	private RosterEntryDao mRosterEntryDao;
	private String mAccount;
	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case ROSTER_CHANGE_SUCCESS:
				L.i(tag, "roster更新成功");
				handler.postAtTime(runnable, 10000);
				break;
			case ROSTER_CHANGE_EXCEPTION:
				T.showShort(PersonInfoActivity.this, "添加好友失败");
				break;
			case GET_PERSONINFO:
				mInfo = mPersonInfoDao.getPersonInfo(mAccount);
				refreshUI();
				break;
			case GET_PERSONINFO_EXCEPTION:
				break;
			default:
				break;
			}
		}
	};

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			finish();
		}
	};

	ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppService = ((XmppService.XMPPBinder) service).getService();
			getPersonInfoThread();
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mXmppService = null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personinfo);
		Intent intent1 = new Intent(PersonInfoActivity.this, XmppService.class);
		bindService(intent1, mConnection, Context.BIND_AUTO_CREATE);
		initialize();
	}

	protected void initialize() {
		mRosterEntryDao = new RosterEntryDao(this);
		mPersonInfoDao = new PersonInfoDao(this);
		mPresenceDao = new PresenceDao(this);
		Intent intent2 = getIntent();
		mAccount = intent2.getStringExtra(INTENT_ACCOUNT);

		button1 = (Button) findViewById(R.id.button1);
		mMenuIv = (ImageView) findViewById(R.id.iv_person_menu_btn);
		mImg1Iv = (ImageView) findViewById(R.id.iv_personinfo_img1);
		mImg2Iv = (ImageView) findViewById(R.id.iv_personinfo_img2);
		mImg3Iv = (ImageView) findViewById(R.id.iv_personinfo_img3);
		mNickNameTv = (TextView) findViewById(R.id.tv_personinfo_nickname);
		mAreaTv = (TextView) findViewById(R.id.tv_personinfo_area);
		mAccountTv = (TextView) findViewById(R.id.tv_personinfo_account);
		mSendMsgBtn = (Button) findViewById(R.id.tv_sendmsg_btn);
		mAddfriendBtn = (Button) findViewById(R.id.tv_addfriend_btn);

		mAddfriendBtn.setOnClickListener(this);
		mSendMsgBtn.setOnClickListener(this);
		mImg1Iv.setOnClickListener(this);
		mImg2Iv.setOnClickListener(this);
		mImg3Iv.setOnClickListener(this);
		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Presence presence = mXmppService.getPresenceOfAccount(mAccount);
				L.i(tag, "presence:  " + presence.toXML());
				List<LocalRosterEntity> List = mRosterEntryDao
						.getRosterEntities();
				for (LocalRosterEntity entity : List) {
					L.i(tag, "roster:   " + entity.toString());
				}
			}
		});
	}

	private void refreshUI() {
		if (MyApplication.subscribe(this, mAccount)) {
			mAddfriendBtn.setVisibility(View.GONE);
			mSendMsgBtn.setVisibility(View.VISIBLE);
		} else {
			mAddfriendBtn.setVisibility(View.VISIBLE);
			mSendMsgBtn.setVisibility(View.VISIBLE);
			// mMenuIv.setClickable(false);
		}
		mAccountTv.setText("帐号:  " + mAccount);
		if (mInfo != null) {
			if (!(mInfo.getNickName() == null || mInfo.getNickName().equals(
					"null"))) {
				mNickNameTv.setText(mInfo.getNickName());
			}
			if (!(mInfo.getCtry() == null || mInfo.getCtry().equals("null"))) {
				mAreaTv.setText(mInfo.getCtry());
			}
		}
	}

	private void getPersonInfoThread() {
		if (mXmppService != null
				&& NetworkUtil.NETWORN_NONE != NetworkUtil
						.getNetworkState(this)) {
			if (mThread == null) {
				mThread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							PersonInfoEntity myInfo = mXmppService
									.getPersonInfoByAccount(mAccount);
							if (myInfo != null) {
								mPersonInfoDao.saveOrUpdatePersonInfo(myInfo);
							}
							handler.sendEmptyMessage(GET_PERSONINFO);
						} catch (XMPPException e) {
							e.printStackTrace();
							handler.sendEmptyMessage(GET_PERSONINFO_EXCEPTION);
						} finally {
							synchronized (mThread) {
								mThread = null;
							}
						}
					}
				});
				mThread.start();
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		handler.removeCallbacksAndMessages(null);
		unbindService(mConnection);
	}

	private void addFriendThread() {
		L.i(tag, "添加好友");
		new Thread(new Runnable() {
			@Override
			public void run() {
				L.i(tag,
						"网络："
								+ NetworkUtil
										.getNetworkState(PersonInfoActivity.this));
				L.i(tag, "验证：  " + mXmppService.isLogin());
				if (NetworkUtil.getNetworkState(PersonInfoActivity.this) != NetworkUtil.NETWORN_NONE
						&& mXmppService.isLogin()) {
					try {
						if (mInfo != null && mInfo.getNickName() != null) {
							mXmppService.addRosterItem(mAccount,
									mInfo.getNickName());
						} else {
							mXmppService.addRosterItem(mAccount, mAccount);
						}
						L.i(tag, "添加成功");
						handler.sendEmptyMessage(ROSTER_CHANGE_SUCCESS);
					} catch (XMPPException e) {
						e.printStackTrace();
						L.i(tag, "添加失败");
						handler.sendEmptyMessage(ROSTER_CHANGE_EXCEPTION);
					}
				} else {
					handler.sendEmptyMessage(ROSTER_CHANGE_EXCEPTION);
				}
			}
		}).start();
	}

	private void closePopup() {
		if (mMenuWindow != null && mMenuWindow.isShowing()) {
			mMenuWindow.dismiss();
		}
	}

	private void showPopup(View parent) {
		List<String> mMenuNameList = new LinkedList<String>();
		mMenuNameList.add("设置备注");
		mMenuNameList.add("加入黑名单");
		mMenuNameList.add("删除好友");
		if (mMenuWindow != null) {
			mMenuWindow.dismiss();
			mMenuWindow = null;
		}
		mMenuWindow = new ListPopupWindow(this);
		if (mMenuAdapter == null) {
			mMenuAdapter = new MenuAdapter(mMenuNameList);
		}
		mMenuWindow.setModal(true);
		mMenuWindow.setContentWidth(getResources().getDimensionPixelSize(
				R.dimen.popo_menu_dialog_width));
		mMenuWindow.setAdapter(mMenuAdapter);
		mMenuWindow.setOnItemClickListener(this);
		mMenuWindow.setAnchorView(mMenuIv);
		if (mMenuWindow != null && !mMenuWindow.isShowing()) {
			mMenuWindow.show();
		}
		mMenuWindow.getListView().setDividerHeight(1);
	}

	class MenuAdapter extends BaseAdapter {
		List<String> menuName;

		public MenuAdapter(List<String> list) {
			this.menuName = list;
		}

		@Override
		public int getCount() {
			return menuName.size();
		}

		@Override
		public Object getItem(int position) {
			return menuName.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(parent.getContext()).inflate(
					R.layout.menu_listitem_layout, null);
			TextView tv = (TextView) convertView
					.findViewById(R.id.tv_menu_listitem);
			tv.setText(menuName.get(position));
			return convertView;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_sendmsg_btn:
			Intent intent = new Intent(this, ChatActivity.class);
			intent.putExtra(ChatActivity.INTENT_ACCOUNT, mAccount);
			startActivity(intent);
			break;
		case R.id.tv_addfriend_btn:
			addFriendThread();
			break;

		default:
			break;
		}
	}

	public void btnClick(View v) {
		switch (v.getId()) {
		case R.id.iv_person_menu_btn:
			showPopup(v);
			break;
		case R.id.iv_person_back:
			finish();
			break;

		default:
			break;
		}
	}

	public void back(View view) {
		finish();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		closePopup();
		switch (arg2) {
		case 0:
			break;
		case 1:
			break;
		case 2:// 删除好友

			new Thread(new Runnable() {
				@Override
				public void run() {
					if (NetworkUtil.getNetworkState(PersonInfoActivity.this) != NetworkUtil.NETWORN_NONE
							&& mXmppService != null && mXmppService.isLogin()) {
						try {
							mXmppService.removeRosterItem(mAccount);
							mPresenceDao.deleInfoByAccount(mAccount);
							handler.sendEmptyMessage(ROSTER_CHANGE_SUCCESS);
						} catch (XMPPException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
			break;
		default:
			break;
		}
	}
}
